<template>
  <view class="payment-result">
    <!-- 状态展示区 -->
    <view class="result-container" :class="{'success': paymentStatus === 'success', 'fail': paymentStatus === 'fail'}">
      <view class="status-icon">
        <text v-if="paymentStatus === 'success'" class="iconfont icon-success">✓</text>
        <text v-else-if="paymentStatus === 'fail'" class="iconfont icon-fail">✕</text>
        <text v-else class="iconfont icon-loading">⟳</text>
      </view>
      <view class="status-text">{{ statusText }}</view>
      <view class="status-desc">{{ statusDesc }}</view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-info-card" v-if="orderInfo.id">
      <view class="card-title">订单信息</view>
      <view class="info-item">
        <text class="item-label">订单编号</text>
        <text class="item-value">{{ orderInfo.orderNumber }}</text>
      </view>
      <view class="info-item">
        <text class="item-label">服务名称</text>
        <text class="item-value">{{ orderInfo.serviceName }}</text>
      </view>
      <view class="info-item">
        <text class="item-label">服务选项</text>
        <text class="item-value">{{ orderInfo.serviceOption }}</text>
      </view>
      <view class="info-item">
        <text class="item-label">服务时间</text>
        <text class="item-value">{{ orderInfo.serviceTime }}</text>
      </view>
      <view class="info-item total-price">
        <text class="item-label">支付金额</text>
        <text class="item-value">¥{{ orderInfo.totalAmount }}</text>
      </view>
    </view>
    
    <!-- 按钮区域 -->
    <view class="action-btns">
      <button class="btn primary-btn" @click="viewOrderDetail">查看订单详情</button>
      <button class="btn secondary-btn" @click="backToHome">返回首页</button>
    </view>
    
    <!-- 推荐服务 -->
    <view class="recommend-section" v-if="paymentStatus === 'success' && recommendServices.length > 0">
      <view class="section-title">
        <text>为您推荐</text>
      </view>
      <scroll-view scroll-x class="recommend-scroll" show-scrollbar="false">
        <view class="recommend-container">
          <view 
            class="recommend-item" 
            v-for="(item, index) in recommendServices" 
            :key="index"
            @click="goToServiceDetail(item.id)"
          >
            <image :src="item.image" mode="aspectFill" class="recommend-image" />
            <view class="recommend-info">
              <text class="recommend-name">{{ item.name }}</text>
              <text class="recommend-price">¥{{ item.price }}起</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';

// 初始化store
const store = useStore();

// 支付状态: success, fail, loading
const paymentStatus = ref('loading');
const paymentResult = ref({});
const orderInfo = ref({});
const recommendServices = ref([]);

// 计算属性：状态文本
const statusText = computed(() => {
  switch(paymentStatus.value) {
    case 'success':
      return '支付成功';
    case 'fail':
      return '支付失败';
    default:
      return '正在处理';
  }
});

// 计算属性：状态描述
const statusDesc = computed(() => {
  switch(paymentStatus.value) {
    case 'success':
      return `您已成功支付¥${orderInfo.value.totalAmount || 0}`;
    case 'fail':
      return paymentResult.value.message || '支付过程中发生错误，请稍后重试';
    default:
      return '正在处理您的支付，请稍候...';
  }
});

// 生命周期钩子
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  console.log('支付结果页面参数:', options);
  
  if (!options.orderId) {
    uni.showToast({
      title: '缺少订单信息',
      icon: 'none'
    });
    setTimeout(() => {
      backToHome();
    }, 1000);
    return;
  }
  
  // 模拟加载支付结果
  setTimeout(() => {
    // 从服务器获取支付结果
    // 这里模拟一个成功的结果
    paymentStatus.value = options.status || 'success';
    paymentResult.value = {
      status: paymentStatus.value,
      message: paymentStatus.value === 'success' ? '支付成功' : '支付失败：余额不足'
    };
    
    // 获取订单详情
    getOrderInfo(options.orderId);
    
    // 如果支付成功，获取推荐服务
    if (paymentStatus.value === 'success') {
      getRecommendServices();
    }
  }, 1000);
});

// 获取订单详情
const getOrderInfo = (orderId) => {
  // 实际项目中应该从API获取订单详情
  // 这里使用模拟数据
  orderInfo.value = {
    id: orderId,
    orderNumber: 'DD' + new Date().getTime(),
    serviceName: '快递代拿服务',
    serviceOption: '普通件 (0-2kg)',
    serviceTime: '今天 18:00-19:00',
    totalAmount: 5.00
  };
};

// 获取推荐服务
const getRecommendServices = () => {
  // 从Vuex获取服务列表，筛选推荐服务
  store.dispatch('service/fetchServiceList')
    .then(() => {
      const allServices = store.state.service.serviceList;
      // 随机选择3个服务作为推荐
      if (allServices && allServices.length > 0) {
        const shuffled = [...allServices].sort(() => 0.5 - Math.random());
        recommendServices.value = shuffled.slice(0, 3).map(s => ({
          id: s.id,
          name: s.name,
          price: s.price,
          image: s.images[0]
        }));
      }
    })
    .catch(error => {
      console.error('获取推荐服务失败', error);
    });
};

// 查看订单详情
const viewOrderDetail = () => {
  uni.navigateTo({
    url: `/pages/service/order-detail?id=${orderInfo.value.id}`
  });
};

// 返回首页
const backToHome = () => {
  uni.switchTab({
    url: '/pages/home/index'
  });
};

// 跳转到服务详情
const goToServiceDetail = (serviceId) => {
  uni.navigateTo({
    url: `/pages/service/detail?id=${serviceId}`
  });
};
</script>

<style lang="scss" scoped>
.payment-result {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.result-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 20px;
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  
  &.success {
    .status-icon {
      background-color: #e8f7ee;
      .icon-success {
        color: #07c160;
      }
    }
    .status-text {
      color: #07c160;
    }
  }
  
  &.fail {
    .status-icon {
      background-color: #fef0f0;
      .icon-fail {
        color: #f56c6c;
      }
    }
    .status-text {
      color: #f56c6c;
    }
  }
}

.status-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  
  .iconfont {
    font-size: 40px;
    font-weight: 300;
  }
  
  .icon-loading {
    color: #909399;
    animation: spin 1.2s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.status-text {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.status-desc {
  font-size: 14px;
  color: #606266;
}

.order-info-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.total-price {
    margin-top: 6px;
    padding-top: 12px;
    border-top: 1px dashed #f0f0f0;
    font-weight: 500;
    
    .item-value {
      color: #f56c6c;
      font-weight: 600;
    }
  }
}

.item-label {
  color: #909399;
  font-size: 14px;
}

.item-value {
  color: #333;
  font-size: 14px;
}

.action-btns {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 30px;
}

.btn {
  height: 44px;
  line-height: 44px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  text-align: center;
  
  &.primary-btn {
    background-color: #07c160;
    color: #fff;
  }
  
  &.secondary-btn {
    background-color: #fff;
    color: #333;
    border: 1px solid #dcdfe6;
  }
}

.recommend-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  position: relative;
  
  &::before {
    content: "";
    position: absolute;
    left: -8px;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 16px;
    background-color: #07c160;
    border-radius: 3px;
  }
}

.recommend-scroll {
  width: 100%;
}

.recommend-container {
  display: inline-flex;
  padding: 4px 0;
}

.recommend-item {
  width: 140px;
  margin-right: 12px;
  
  &:last-child {
    margin-right: 0;
  }
}

.recommend-image {
  width: 140px;
  height: 100px;
  border-radius: 8px;
  background-color: #f5f5f5;
  margin-bottom: 8px;
}

.recommend-info {
  display: flex;
  flex-direction: column;
}

.recommend-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recommend-price {
  font-size: 13px;
  color: #f56c6c;
  font-weight: 500;
}
</style>
